<?php


namespace App\Utils\Service\Syj;


use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class weChatService
{
    private static $instance = null;
    private $appKey;
    private $appSecret;
    public function __construct()
    {
        $this->appKey = Config::get('services.weChat.app_key');
        $this->appSecret = Config::get('services.weChat.app_secret');
    }

    public static function getInstance(){
        if(self::$instance == null){
            if(self::$instance = new weChatService());
        }
        return self::$instance;
    }

    public function sendMessage($phone){
        //构造消息内容
        $message = [
            'touser'=> $phone,
            'template_id'=>'模板id',
            'data' => [
                'first' => array('value' => '您好，您已成功登录系统！'),
                'keyword1' => array('value' => '系统名称'),
                'keyword2' => array('value' => date('Y-m-d H:i:s', time())),
                'remark' => array('value' => '感谢您的使用！'),
            ],
        ];
        //发送消息模板
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $this->getAccessToken();
        $response = Http::post($url, $message);
        $result = json_decode($response->body(), true);
        if ($result['errcode'] == 0) {
            Log::info("发送模板消息成功，openid: $phone");
            return true;
        } else {
            Log::error("发送模板消息失败，openid: $phone . 错误信息: " . $result['errmsg']);
            return false;
        }
    }

    private function getAccessToken()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appKey}&secret={$this->appSecret}";
        $response = Http::get($url);
        $result = json_decode($response->body(), true);
        return $result['access_token'];
    }

}
